package com.itheima.aop;

import com.itheima.domain.SysLog;
import com.itheima.mapper.SysLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class LogAop {
    /**
     * 1.切入点表达式
     *
     * 2.@annotation(com.itheima.anno.LogAnno) 给注解切面，只要添加了次注解的方法，都会进行增强
     *
     * 什么是注解 ？ 给JVM 编译器看的
     * 什么是注释 ？ 给程序员看的
     *
     */
    @Pointcut("@annotation(com.itheima.anno.LogAnno)")
    public void pt1(){}
    @Autowired
    private SysLogMapper sysLogMapper;

    /**
     * 通知
     */
    @Around("pt1()")

    public Object around(ProceedingJoinPoint pjp)  {

        System.out.println("我打印了.....");
        Object proceed = null;
        try {
            proceed = pjp.proceed();
        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            //todo 添加日志记录
            SysLog log = new SysLog();
            log.setUsername("admin");
            log.setMethod(pjp.getSignature().getDeclaringTypeName()+"."+pjp.getSignature().getName());
            log.setParams(Arrays.toString(pjp.getArgs()));
            log.setCreated(new Date());
            log.setOperation(pjp.getSignature().getName());
            //todo 调用mapper 存储到 数据库即可
            sysLogMapper.save(log);
            System.out.println("添加日志到数据库:"+log);
        }

        return proceed;
    }
}
